package xu.zhi.qing.utils;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.springframework.web.multipart.MultipartFile;
import xu.zhi.qing.common.constant.Configuration;
import xu.zhi.qing.exception.FileUploadException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.File;
import java.io.IOException;

/**
 * 缩略图工具
 *
 * @author Lenovo_pc
 */
public class ThumbnailUtil {

    //缩略图的宽高
    public static final Integer LENGTH = 200;

    /**
     * 将指定文件生成缩略图,缩略图居中，宽高相等，图片按比例缩放，四周空白处透明背景
     *
     * @param filepath
     * @return
     * @throws IOException
     */
    public static String createThumbnail( String filepath) throws FileUploadException {
        try {
            String fPath = Configuration.DEFAULT_UPLAOD_TRUE_DIR+ filepath;
            Image sourceImg = ImageIO.read(new File(Configuration.DEFAULT_UPLAOD_TRUE_DIR+ filepath));
            int sourceWidth = sourceImg.getWidth(null);
            int sourceHeight = sourceImg.getHeight(null);

            String filename = FileUtil.renamePng();
            String path = Configuration.DEFAULT_UPLAOD_TRUE_DIR+ Configuration.MINI_IMG_DIR;
            String thumbnailPath = path + filename;
            File dir = new File(path);
            if (!dir.exists()) {
                // 如目录不存在就创建新目录
                dir.mkdirs();
            }
            if (sourceWidth > sourceHeight) {
                clip(fPath, thumbnailPath, sourceHeight, sourceHeight);
            } else {
                clip(fPath, thumbnailPath, sourceWidth, sourceWidth);
            }
            return Configuration.MINI_IMG_DIR  + filename;
        } catch (Exception e) {
            e.printStackTrace();
            throw new FileUploadException("生成缩略图异常！");
        }
    }

    private static void clip(String sourceFile, String targetFile, int width, int height) throws Exception {
        Thumbnails.of(sourceFile)
                .sourceRegion(Positions.CENTER, width, height)
                .size(LENGTH, LENGTH)
                .keepAspectRatio(false)
                .toFile(targetFile);
    }
}
